package com.newbsd.web.maventest.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.newbsd.web.maventest.dao.PageDao;
import com.newbsd.web.maventest.pojo.Order;

import com.newbsd.web.maventest.util.pageUtil;

/**  
*   
* @author ZHM
* 
*/
public class PageDaoImpl implements PageDao{

	@Override
	public pageUtil getPage(int pageNo, int pageSize) {
		 Connection conn = null;
		List<Order> list = new ArrayList<Order>();
		pageUtil page = null;
		try {
			//获取总数据条数

			Context context = new InitialContext();
			DataSource datasource = (DataSource)context.lookup("java:comp/env/jdbc/maventest");
			conn = ((PreparedStatement) datasource).getConnection();
			int totalCount = 0;
			PreparedStatement pstmt =
					conn.prepareStatement("select count(orderId) from orders");
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				totalCount = rs.getInt(1);
			}
			pstmt = conn.prepareStatement("select * from orders limit" + (pageNo-1)*pageSize+","+pageSize);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				Order order = new Order();
				order.setCert(rs.getInt(1));
				order.setCstatus(rs.getInt(2));
				order.setDestination(rs.getString(3));
				order.setOrderid(rs.getInt(4));
				order.setOrigin(rs.getString(5));
				order.setPrice(rs.getDouble(6));
				order.setPstatus(rs.getInt(7));
				order.setTicketid(rs.getInt(8));
				order.setTrainno(rs.getString(9));
				order.setUsername(rs.getString(10));
				list.add(order);
			}
			 page = new pageUtil(pageSize, totalCount);
			page.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		 if(conn!=null) {
			 try {
				conn.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
		 }
		}
		return page;
	}

}
